using UnityEngine;
using QFramework;
using QAssetBundle;

namespace ProjectSurvivor
{
    public partial class Ball : ViewController
    {
        void Start()
        {
            // Code Here
            SelfRigidbody2D.velocity = new Vector2(UnityEngine.Random.Range(-1.0f, 1.0f), UnityEngine.Random.Range(-1.0f, 1.0f)
                * UnityEngine.Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2));
            Global.SuperBasketball.RegisterWithInitValue((unLocked) =>
            {
                if(unLocked)
                {
                    this.LocalScale(3);
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
            HurtBox.OnTriggerEnter2DEvent((collider) =>
            {
               var hurtBox = collider.GetComponent<HurtAndHitBox>();
                if (hurtBox)
                {
                    if (hurtBox.Owner.CompareTag("Enemy")||hurtBox.Owner.CompareTag("EnemyFly"))
                    {
                        var enemy = hurtBox.Owner.GetComponent<IEnemy>();
                        var damagesTimes = Global.SuperBasketball.Value ? Random.Range(2,3+1): 1;
                        DemageSystem.CalculateDemage(Global.BasketBallDemage.Value * damagesTimes, enemy);
                        if (UnityEngine.Random.Range(0, 1f) < 0.5f && collider && collider.attachedRigidbody && Player.Default)
                        {
                            collider.attachedRigidbody.velocity = (collider.NormalizedDirection2DFrom(this) * 5 +
                            (collider.NormalizedDirection2DFrom(Player.Default) * 10));
                        }
                    }
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private void OnCollisionEnter2D(Collision2D other)
        {
            var normal = other.GetContact(0).normal;
            if (normal.x > normal.y)
            {
                SelfRigidbody2D.velocity = new Vector2(SelfRigidbody2D.velocity.x, Mathf.Sign(SelfRigidbody2D.velocity.y) * UnityEngine.Random.Range(0.5f, 1.5f) *
                    UnityEngine.Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2)
                    );

                SelfRigidbody2D.angularVelocity = UnityEngine.Random.Range(-360, 360);

            }
            else
            {
                var rb = SelfRigidbody2D;
                rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * UnityEngine.Random.Range(0.5f, 1.5f) * UnityEngine.Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2), rb.velocity.y);
                rb.angularVelocity = UnityEngine.Random.Range(-360f, 360f);
            }
            AudioKit.PlaySound(Sfx.BALL);
        }
    }
}
